package com.xiaoshuidi.cloud.module.report.xxljob;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.OwnerIncomeDetailReportDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.OwnerIncomeDetailDayReportMapper;
import com.xiaoshuidi.cloud.module.report.service.finance.OwnerIncomeDetailReportService;
import com.xiaoshuidi.cloud.module.report.utils.DateUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收入明细处理 job 每天凌晨3:20跑一次
 * 需将汇总明细的数据进行再次汇总统计到月
 */
@Component
@Slf4j
public class OwnerIncomeDetailJob {

    @Resource
    private OwnerIncomeDetailReportService ownerIncomeDetailReportService;

    @Resource
    private OwnerIncomeDetailDayReportMapper ownerIncomeDetailDayReportMapper;

    @XxlJob("ownerIncomeDetailJob")
    @TenantIgnore
    public void execute() {
        //获取昨天所在当月所有的明细
        String currentMonth = DateUtils.getYesterdayMonth();
        List<OwnerIncomeDetailReportDO> list = ownerIncomeDetailDayReportMapper.selectOwnerDetailsInCurrentMonth(currentMonth);
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        handlerDetails(list,currentMonth);
    }

    private void handlerDetails(List<OwnerIncomeDetailReportDO> list,String currentMonth) {
        //查询当月是否已经生成过汇总明细收入
        List<Long> contractIds = list.stream().map(OwnerIncomeDetailReportDO::getContractId).collect(Collectors.toList());
        List<OwnerIncomeDetailReportDO> reportDOS = ownerIncomeDetailReportService.selectDetailsInCurrentMonthAndContractIds(currentMonth, contractIds);
        if (CollectionUtils.isEmpty(reportDOS)) {
            ownerIncomeDetailReportService.insertBatch(list);
        } else {
            //不为空
            list.forEach(e -> {
                reportDOS.forEach(report -> {
                    if (e.getContractId().equals(report.getContractId())) {
                        e.setId(report.getId());
                    }
                });
            });
            List<OwnerIncomeDetailReportDO> updateList = list.stream().filter(e -> e.getId() != null).collect(Collectors.toList());
            List<OwnerIncomeDetailReportDO> insertList = list.stream().filter(e -> e.getId() == null).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(updateList)) {
                ownerIncomeDetailReportService.updateBatch(updateList);
            }
            if (CollectionUtils.isNotEmpty(insertList)) {
                ownerIncomeDetailReportService.insertBatch(insertList);
            }
        }
    }


}